package cn.lj.ykt.service.impl;

import cn.lj.ykt.api.LoginFeignAPI;
import cn.lj.ykt.businessconstant.Constant;
import cn.lj.ykt.domain.Login;
import cn.lj.ykt.domain.User;
import cn.lj.ykt.domain.UserAccount;
import cn.lj.ykt.domain.UserBaseInfo;
import cn.lj.ykt.dto.RedisPhoneCode;
import cn.lj.ykt.dto.RegisterParamDto;
import cn.lj.ykt.exception.GlobleBusinessException;
import cn.lj.ykt.mapper.UserMapper;
import cn.lj.ykt.result.JSONResult;
import cn.lj.ykt.service.IUserService;
import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.baomidou.mybatisplus.mapper.Wrapper;
import com.baomidou.mybatisplus.service.impl.ServiceImpl;
import com.google.gson.JsonObject;
import io.seata.spring.annotation.GlobalTransactional;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;
import com.alibaba.fastjson.JSONObject;

import java.math.BigDecimal;


/**
 * <p>
 * 会员登录账号 服务实现类
 * </p>
 *
 * @author whale
 * @since 2025-08-28
 */
@Service
public class UserServiceImpl extends ServiceImpl<UserMapper, User> implements IUserService {

    @Autowired
    private RedisTemplate<Object, Object> redisTemplate;

    @Autowired
    private LoginFeignAPI loginFeignAPI;

    @Autowired
    private  UserAccountServiceImpl userAccountServiceImpl;

    @Autowired
    private UserBaseInfoServiceImpl userBaseInfoServiceImpl;

    /**
     * 手机号校验&数据插入
     * @param registerParamDto
     * @return
     */
    @GlobalTransactional(rollbackFor = Exception.class)
    @Override
    public void phoneRegister(RegisterParamDto registerParamDto) {

        String mobile = registerParamDto.getMobile();
        String password = registerParamDto.getPassword();
        Integer regChannel = registerParamDto.getRegChannel();
        String smsCode = registerParamDto.getSmsCode();

        //1.校验一个都不能为空
        if(StringUtils.isEmpty( mobile)
        || StringUtils.isEmpty(password)
        || StringUtils.isEmpty(regChannel)
        || StringUtils.isEmpty(smsCode)){
            throw new GlobleBusinessException("参数不能为空");
        }


        //2.从redis中取得验证码，判断死否相等
        String key = Constant.PHONE_REGISTER + mobile;
        Object o = redisTemplate.opsForValue().get(key);

        if (StringUtils.isEmpty(o)){
            throw new GlobleBusinessException("验证码不存在");
        }

        RedisPhoneCode redisPhoneCode = (RedisPhoneCode) o;
        String code = ((RedisPhoneCode) o).getCode();
        if(!code.equals(smsCode)){
            throw new GlobleBusinessException("验证码输入错误");
        }

        //3. 验证一下用户表中是否已经注册
        Wrapper<User> www = new EntityWrapper<User>();
        www.eq("phone",mobile);
        User user = this.selectOne(www);

        if (user != null){
            throw new GlobleBusinessException("用户已经注册");
        }

        //4.  插入数据库 t_user, t_user_account, t_user_base_info, t_login_log

        //插入t_login
        Login login = new Login();
        login.setUsername(mobile);
        login.setPassword(password);
        login.setType(1);
        login.setEnabled(true);
        login.setAccountNonExpired(true);
        login.setCredentialsNonExpired(true);
        login.setAccountNonLocked(true);

        //获取自增id---这个不能直接获取对象,这个通过openfeign传输过来是二进制过来的,识别不了对象
        JSONResult jsonResult = loginFeignAPI.register(login);
        Object data = jsonResult.getData();
        String jsonString = JSONObject.toJSONString(data);
        Login LoginDB = JSONObject.parseObject(jsonString, Login.class);

        //插入t_user
        User userDB = new User();
        userDB.setPhone(mobile);
        userDB.setCreateTime(System.currentTimeMillis());
        userDB.setUpdateTime(System.currentTimeMillis());
        userDB.setNickName( mobile);
        userDB.setLoginId(LoginDB.getId());
        this.insert(userDB);

        //插入t_user_account--没有主键,根据t_user的主键来确定用户--外键
        UserAccount userAccount = new UserAccount();
        userAccount.setId(userDB.getId());
        userAccount.setUsableAmount(new BigDecimal(0));
        userAccount.setFrozenAmount(new BigDecimal(0));
        userAccount.setCreateTime(System.currentTimeMillis());
        userAccount.setUpdateTime(System.currentTimeMillis());
        userAccountServiceImpl.insert(userAccount);

        //插入t_user_base_info--没有主键,根据t_user的主键来确定用户--外键
        UserBaseInfo userBaseInfo = new UserBaseInfo();
        userBaseInfo.setCreateTime(System.currentTimeMillis());
        userBaseInfo.setUpdateTime(System.currentTimeMillis());
        userBaseInfo.setRegChannel(regChannel);
        userBaseInfo.setId(userDB.getId());
        userBaseInfoServiceImpl.insert(userBaseInfo);

        redisTemplate.delete(Constant.PHONE_REGISTER + mobile);
    }
}
